<?php
	
	$tplList = new XTemplate('view/category/list.htm');
	$category_id = _POST('id');
	$tplList->assign('baseUrl', $baseUrl);

	if(is_numeric($category_id)){
		$sql = "SELECT * FROM tblcategory WHERE category_id=$category_id";
		$category = $db->fetchOne($sql);
		$tplList->assign('category', $category);
		$title = $category['category_name'] .' - ';
		
		$_SESSION['category_name'] = $category['category_name'];
		$sql = "SELECT * FROM tblproduct WHERE category_id=$category_id AND special=0";
		$products = $db->fetchAll($sql);
		
		$limit 		= 12;
		$page		= (_POST('pi'))?_POST('pi'):1;
		$offset		= ($page-1)*$limit;
		$totalRow 	= count($products);
		
		$sql = "SELECT * FROM tblproduct WHERE category_id=$category_id AND special=0 LIMIT $offset,$limit";
		$products = $db->fetchAll($sql);
		
		//SPECIAL PRODUCT
		
		$sql = "SELECT * FROM tblproduct WHERE category_id=$category_id AND special=1";
		$specials = $db->fetchAll($sql);
		if($totalRow<1 && count($specials)<1){
			$tplList->parse('LIST.NOPRODUCT');
		}
		foreach($specials as $special){
			$imagespecial  = $db->fetchOne("SELECT img_url FROM tblproduct_img WHERE product_id =".$special['product_id']."  AND basic_img =1");
		
			$imagespecial['imgurl'] = '/media/product/images/base/no-image.png';
			if($imagespecial['img_url'])
				$special['imgurl'] = $imagespecial['img_url'];
			$tplList->insert_loop('LIST.LISPECIAL', array('LISPECIAL'=>$special));
			break;
		}
		
		
		
		foreach($products as $product){
			$product['price'] = formatPrice($product['price']) . ' đ';
			$image 		= $db->fetchOne("SELECT img_url FROM tblproduct_img WHERE product_id =".$product['product_id']."  AND basic_img =1");
		
			$product['imgurl'] = '/media/product/images/base/no-image.png';
			if($image['img_url'])
				$product['imgurl'] = $image['img_url'];
			
			//List color
			$colors = $db->fetchAll("SELECT * FROM tblproduct_color WHERE product_id = ".$product['product_id'].' GROUP BY color_code');
			foreach($colors as $color){
				$tplList->insert_loop('LIST.LISTPRODUCT.COLOR', array('COLOR'=>$color));
			}
			$tplList->insert_loop('LIST.LISTPRODUCT', array('LISTPRODUCT'=>$product));
			
		}
	}
	$pages = pagenavigator($page, $totalRow, $limit, 5, "?c=category&a=list&id=$category_id");
	$tplList->assign('pages', $pages);
	$tplList->parse('LIST');
	$content = $tplList->text('LIST');